using System;
using System.Collections.Generic;
using System.Text;
using Musicman.Entities;
using Musicman.DAL;
using Musicman.Common;
using Musicman.Entities.BusinessEntities;
using System.Collections;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data;
using System.Security.Cryptography;
using System.IO;

namespace Musicman.Business
{
    public class DataManager
    {
        # region singleton definition
        static readonly DataManager instance = new DataManager();
        
        public static DataManager Instance
        {
            get
            {
                return instance;
            }
        }
        static DataManager()
        {
            
        }
        # endregion

        #region SearchServiceMethods
        public bool SaveSearchJob(Searchjob job)
        {
            bool res = true;
            try
            {
                res = SearchjobDAO.SaveSearchjob(job, true);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to save search job to database", ex);
            }
            return res;
        }

        public void ClearPreviousResult()
        {
            try
            {
                SearchjobDAO.ClearAllData();
            }
            catch (Exception ex)
            {
                LogManager.LogException("Unable to delete previous results", ex);
            }
        }

        public bool ClearJobData(Searchjob job)
        {
            bool res = true;
            try
            {
                SearchjobDAO.ClearJobData(job);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to delete previous results", ex);
            }
            return res;
        }

        public Searchjob GetSearchJob(string name, string criteria, byte type)
        {
            Searchjob res = null;
            try
            {
                string where = String.Format(" WHERE NAME = '{0}' AND TYPE = {1}", name, type);
                List<Searchjob> list = SearchjobDAO.LoadSearchjobsAllData(where, "");
                if (list.Count == 1)
                {
                    res = list[0];
                    res.Allcriteria = criteria;
                }
                if (list.Count == 0)
                {
                    res = new Searchjob();
                    res.Name = name;
                    res.Allcriteria = criteria;
                    res.Type = type;
                }
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search job", ex);
            }
            return res;
        }

        public bool DeleteListSearchFiles(List<Searchfile> deleteList)
        {            
            bool res = true;
            try
            {
                res = SearchfileDAO.DeleteListSearchfile(deleteList);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to delete list of search files", ex);
            }
            return res;
        }

        public Searchfile GetSearchFile(long fileID)
        {
            Searchfile res = null;
            try
            {
                string where = String.Format(" WHERE SEARCHFILEID = '{0}'", fileID);
                List<Searchfile> list = SearchfileDAO.LoadSearchfiles(where, "");
                if (list.Count == 1)
                {
                    res = list[0];
                }
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search job", ex);
            }
            return res;
        }

        public bool SaveSearchFile(Searchfile sf)
        {
            bool res = false;
            try
            {
                res = SearchfileDAO.SaveSearchfile(sf);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to save search file", ex);
            }
            return res;
        }

        public List<User> GetUserList()
        {
            List<User> res = null;
            try
            {
                res = UsersDAO.LoadUserss("", "");
            }
            catch (Exception ex)
            {
                LogManager.LogException("Unable to get list of users", ex);
            }
            return res;
        }

        public List<User> GetMailingList()
        {
            List<User> res = null;
            try
            {
                res = UsersDAO.LoadUserss(" WHERE MAILRQ = 1", "");
            }
            catch (Exception ex)
            {
                LogManager.LogException("Unable to get list of users", ex);
            }
            return res;
        }

        #endregion

        #region WebApplicatoinMethods

        #region SearchJob methods
        public List<Searchjob> GetAllSearchJobs()
        {
            List<Searchjob> res = null;
            try
            {
                res = SearchjobDAO.LoadSearchjobs("", " ORDER BY SEARCHJOBID DESC");
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search jobs", ex);
            }
            return res;
        }
        #endregion

        #region SearchFiles

        public List<SearchResult> SearhFiles(int top, long jobID, string filename)
        {
            List<SearchResult> res = new List<SearchResult>();
            try
            {
                string topStr = (top == 0) ? "" : String.Format(" TOP {0} ", top);
                StringBuilder where = new StringBuilder();
                where.AppendFormat(" WHERE JOB.SEARCHJOBID = {0} ", jobID);
                filename = filename.Replace("'", "''");
                while (filename.Contains("\""))
                {
                    int index1 = filename.IndexOf('"');
                    int index2 = filename.IndexOf('"', index1 + 1);
                    string part = "";
                    if (index2 == -1)
                    {
                        part = filename.Replace("\"", "");
                        filename = "";
                    } 
                    else 
                    {
                        part = filename.Substring(index1 + 1, index2 - index1 - 1);
                        filename = filename.Substring(0, (index1 == 0) ? 0 : index1 - 1) + filename.Substring(index2 + 1);
                    }
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", part);
                }
                string[] words = filename.Split(' ');
                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i];
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", word.Trim());
                }
                res = SearchfileDAO.SearchFiles(topStr, where.ToString(), "");
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search files", ex);
            }
            return res;
        }

        public List<SearchResult> SearhFiles(long jobID, string filename)
        {
            return SearhFiles(0, jobID, filename);
        }

        public SearchResult GetSearchResult(long searchFileID)
        {
            SearchResult res = null;
            try
            {
                string where = String.Format(" WHERE FILEE.SEARCHFILEID = {0}", searchFileID);
                List<SearchResult> lRes = SearchfileDAO.SearchFiles("", where, "");
                if (lRes.Count == 1)
                {
                    res = lRes[0];
                }
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search files", ex);
            }
            return res;
        }

        public List<SearchResult> GetPendingDownloads(long userID)
        {
            List<SearchResult> res = new List<SearchResult>();
            try
            {
                string where = String.Format(" WHERE DOWNLOADS.USERID = {0}", userID);
                res = SearchfileDAO.GetPendingDownloads(where, "");
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive pending files", ex);
            }
            return res;
        }

        public List<SearchResult> GetTopDownloads(long jobID, string filename, int count)
        {
            List<SearchResult> res = new List<SearchResult>();
            try
            {
                string topStr = (count == 0) ? "" : String.Format(" TOP {0} ", count);
                StringBuilder where = new StringBuilder();
                where.AppendFormat(" WHERE JOB.SEARCHJOBID = {0} ", jobID);
                filename = filename.Replace("'", "''");
                while (filename.Contains("\""))
                {
                    int index1 = filename.IndexOf('"');
                    int index2 = filename.IndexOf('"', index1 + 1);
                    string part = "";
                    if (index2 == -1)
                    {
                        part = filename.Replace("\"", "");
                        filename = "";
                    }
                    else
                    {
                        part = filename.Substring(index1 + 1, index2 - index1 - 1);
                        filename = filename.Substring(0, (index1 == 0) ? 0 : index1 - 1) + filename.Substring(index2 + 1);
                    }
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", part);
                }
                string[] words = filename.Split(' ');
                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i];
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", word.Trim());
                }
                res = SearchfileDAO.GetTopDownloaded(topStr, where.ToString());
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive pending files", ex);
            }
            return res;
        }

        public List<SearchResult> GetTopRated(long jobID, string filename, int count)
        {
            List<SearchResult> res = new List<SearchResult>();
            try
            {
                string topStr = (count == 0) ? "" : String.Format(" TOP {0} ", count);
                StringBuilder where = new StringBuilder();
                where.AppendFormat(" WHERE JOB.SEARCHJOBID = {0} ", jobID);
                filename = filename.Replace("'", "''");
                while (filename.Contains("\""))
                {
                    int index1 = filename.IndexOf('"');
                    int index2 = filename.IndexOf('"', index1 + 1);
                    string part = "";
                    if (index2 == -1)
                    {
                        part = filename.Replace("\"", "");
                        filename = "";
                    }
                    else
                    {
                        part = filename.Substring(index1 + 1, index2 - index1 - 1);
                        filename = filename.Substring(0, (index1 == 0) ? 0 : index1 - 1) + filename.Substring(index2 + 1);
                    }
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", part);
                }
                string[] words = filename.Split(' ');
                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i];
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", word.Trim());
                }
                res = SearchfileDAO.GetTopRated(topStr, where.ToString());
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive pending files", ex);
            }
            return res;
        }

        public List<SearchResult> SearchFilesRandom(long jobID, string filename, int top)
        {
            List<SearchResult> res = new List<SearchResult>();
            try
            {
                string topStr = (top == 0) ? "" : String.Format(" TOP {0} ", top);
                StringBuilder where = new StringBuilder();
                where.AppendFormat(" WHERE JOB.SEARCHJOBID = {0} ", jobID);
                filename = filename.Replace("'", "''");
                while (filename.Contains("\""))
                {
                    int index1 = filename.IndexOf('"');
                    int index2 = filename.IndexOf('"', index1 + 1);
                    string part = "";
                    if (index2 == -1)
                    {
                        part = filename.Replace("\"", "");
                        filename = "";
                    }
                    else
                    {
                        part = filename.Substring(index1 + 1, index2 - index1 - 1);
                        filename = filename.Substring(0, (index1 == 0) ? 0 : index1 - 1) + filename.Substring(index2 + 1);
                    }
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", part);
                }
                string[] words = filename.Split(' ');
                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i];
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", word.Trim());
                }
                res = SearchfileDAO.SearchFilesRandom(where.ToString(), " ORDER BY NEWID()", top);
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search files", ex);
            }
            return res;
        }

        public List<SearchResult> SearchLatest(long jobID, string filename, int top)
        {
            List<SearchResult> res = new List<SearchResult>();
            long searchSeqence = GetMaxSearchSequence(jobID);
            try
            {
                string topStr = (top == 0) ? "" : String.Format(" TOP {0} ", top);
                StringBuilder where = new StringBuilder();
                where.AppendFormat(" WHERE JOB.SEARCHJOBID = {0} ", jobID);
                filename = filename.Replace("'", "''");
                while (filename.Contains("\""))
                {
                    int index1 = filename.IndexOf('"');
                    int index2 = filename.IndexOf('"', index1 + 1);
                    string part = "";
                    if (index2 == -1)
                    {
                        part = filename.Replace("\"", "");
                        filename = "";
                    }
                    else
                    {
                        part = filename.Substring(index1 + 1, index2 - index1 - 1);
                        filename = filename.Substring(0, (index1 == 0) ? 0 : index1 - 1) + filename.Substring(index2 + 1);
                    }
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", part);
                }
                string[] words = filename.Split(' ');
                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i];
                    where.AppendFormat(" AND (FILEE.NAME LIKE '%{0}%' OR FOLDER.NAME LIKE '%{0}%')", word.Trim());
                }
                where.AppendFormat(" AND SEARCHSEQUENCE = {0}", searchSeqence);
                res = SearchfileDAO.SearchFiles(topStr, where.ToString(), "");
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search files", ex);
            }
            return res;
        }

        public List<SearchResult> SearchFolder(long sercFileId, string loacation)
        {
            List<SearchResult> res = new List<SearchResult>();
            try
            {
                Searchfolder sf = SearchfolderDAO.GetFileFolder(sercFileId)[0];
                DirectoryInfo di = new DirectoryInfo(sf.Name);
                FileInfo[] files = di.GetFiles();
                for (int i = 0; i < files.Length; i++)
                {
                    SearchResult sr = new SearchResult();
                    FileInfo fi = files[i];
                    sr.FileID = 0;
                    sr.Location = loacation;
                    sr.Name = fi.Name;
                    sr.Fullpath = fi.FullName;
                    sr.Length = fi.Length;
                    res.Add(sr);
                }
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive search files from folder", ex);
            }
            return res;
        }

        public long GetMaxSearchSequence(long jobID)
        {
            long res = 0;
            try
            {
                res = SearchfileDAO.GetMaxSearchSequence(jobID);
            }
            catch (Exception ex)
            {
                LogManager.LogException("Unable to retreive max search sequence", ex);
            }
            return res;
        }
        #endregion

        #region Search file stats

        public SearchFileStat GetSearchFileStats(long fileID)
        {
            SearchFileStat res = new SearchFileStat();
            try
            {
                res = SearchFileStatsDAO.GetFileStat(fileID);
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive file sats", ex);
            }
            return res;
        }

        public bool UpdateSearchFileStats(long searchFileID, int mark)
        {
            bool res = false;
            try
            {
                res = SearchFileStatsDAO.UpdateFileStats(searchFileID, mark);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to update search file stats", ex);
            }
            return res;
        }

        #endregion

        #region Users and roles

        public User GetUserInfo(long userID)
        {
            User res = null;
            try
            {
                string where = String.Format(" WHERE USERS.PERSONID = {0}", userID);
                List<User> users = UsersDAO.LoadUserss(where, "");
                if (users != null && users.Count == 1)
                {
                    res = users[0];
                }
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to retreive user info", ex);
            }
            return res;
        }

        public bool CheckUserExist(string emailAddress)
        {
            bool res = false;
            try
            {
                string where = String.Format(" WHERE USERS.EMAILADDRESS = '{0}'", emailAddress);
                res = UsersDAO.CheckUserExist(emailAddress);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to check if user exist", ex);
            }
            return res;
        }

        public bool SaveUser(User user)
        {
            bool res = false;
            try
            {
                res = UsersDAO.SaveUsers(user);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to save user", ex);
            }
            return res;
        }

        public bool CreateNewUser(User user)
        {
            bool res = false;
            DbTransaction transactionObj = null;
            DbConnection conn = null;
            try
            {
                SqlDatabase db = new SqlDatabase(AppSettingsHelper.GetWebConfigValue(Constants.MusicmanConnectionString));
                conn = db.CreateConnection();
                conn.Open();
                transactionObj = conn.BeginTransaction();

                res = UsersDAO.SaveUsers(user, transactionObj, db);
                res = res & RolesDAO.AssignRoleToUser((long)user.Personid, "USER", transactionObj, db);

                transactionObj.Commit();
                transactionObj.Dispose();
                conn.Close();
                conn.Dispose();
            }
            catch (Exception ex)
            {
                res = false;
                if (transactionObj != null)
                {
                    transactionObj.Rollback();
                    transactionObj.Dispose();
                }
                if (conn != null & conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                    conn.Dispose();
                }
                LogManager.LogException("Unable to create new user", ex);
            }
            return res;
        }

        public bool ActivateNewUser(string activationCode)
        {
            bool res = false;
            try
            {
                res = UsersDAO.ActivateNewUser(activationCode);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to create new user", ex);
            }
            return res;
        }

        public User LoggInUser(string email, string password, bool web)
        {
            User res = null;
            try
            {
                string encPass = PassEncrypting(password);
                string where = String.Format(" WHERE EMAILADDRESS = '{0}' AND PASSWORD = '{1}' AND ACTIVATIONCODE IS NULL", email, encPass);
                List<User> users = UsersDAO.LoadUserss(where, "");
                if (users.Count == 1)
                {
                    res = users[0];
                    res.Password = password;
                    if (web)
                    {
                        UsersDAO.UpdateUserStats((long)res.Personid, 1, 0);
                    }
                    else
                    {
                        UsersDAO.UpdateUserStats((long)res.Personid, 0, 1);
                    }
                }
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to login user", ex);
            }
            return res;
        }

        public List<User> GetAllUsers()
        {
            List<User> res = new List<User>();
            try
            {
                res = UsersDAO.LoadUserss("", "");
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to laod user list ", ex);
            }
            return res;
        }

        public string[] GetUserRoles(string email)
        {
            string[] res = null;
            try
            {
                res = RolesDAO.GetUserRoles(email);
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to laod user roles list ", ex);
            }
            return res;
        }

        public int GetLoginCount(long userID)
        {
            int res = 0;
            try
            {
                res = UsersDAO.GetLoginCount(userID);
            }
            catch (Exception ex)
            {
                res = 0;
                LogManager.LogException("Unable to retreive login count", ex);
            }
            return res;
        }

        public int GetClientLoginCount(long userID)
        {
            int res = 0;
            try
            {
                res = UsersDAO.GetClientLoginCount(userID);
            }
            catch (Exception ex)
            {
                res = 0;
                LogManager.LogException("Unable to retreive client login count", ex);
            }
            return res;
        }

        public int GetTotalLoginCount()
        {
            int res = 0;
            try
            {
                res = UsersDAO.GetTotalLoginCount();
            }
            catch (Exception ex)
            {
                res = 0;
                LogManager.LogException("Unable to retreive total logins count", ex);
            }
            return res;
        }

        public int GetTotalClientLoginCount()
        {
            int res = 0;
            try
            {
                res = UsersDAO.GetTotalClientLoginCount();
            }
            catch (Exception ex)
            {
                res = 0;
                LogManager.LogException("Unable to retreive total client login count", ex);
            }
            return res;
        }

        public string PassEncrypting(string originalPass)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            Byte[] originalBytes;
            Byte[] encodedBytes;
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPass);
            encodedBytes = md5.ComputeHash(originalBytes);
            return BitConverter.ToString(encodedBytes);
        }

        #endregion 

        #region Pending downloads

        public bool AddPendingDownloadsList(long userID, List<long> files)
        {
            bool res = true;
            try
            {
                res = PendingDownloadsDAO.AddPendingDownloadsList(userID, files);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to add pending downloads list ", ex);
            }
            return res;
        }

        public bool RemovePendingDownload(long userID, long fileID, int num)
        {
            bool res = false;
            DbTransaction transactionObj = null;
            DbConnection conn = null;
            try
            {
                SqlDatabase db = new SqlDatabase(AppSettingsHelper.GetWebConfigValue(Constants.MusicmanConnectionString));
                conn = db.CreateConnection();
                conn.Open();
                transactionObj = conn.BeginTransaction();

                res = PendingDownloadsDAO.RemovePendingDownload(userID, fileID, transactionObj, db);
                if (num != 0)
                {
                    res = res & PendingDownloadsDAO.UpdateDownloadStats(userID, fileID, num, transactionObj, db);
                }

                transactionObj.Commit();
                transactionObj.Dispose();
                conn.Close();
                conn.Dispose();
            }
            catch (Exception ex)
            {
                res = false;
                if (transactionObj != null)
                {
                    transactionObj.Rollback();
                    transactionObj.Dispose();
                }
                if (conn != null & conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                    conn.Dispose();
                }
                LogManager.LogException("Unable to create new user", ex);
            }
            return res;
        }

        public bool RemovePendingDownloadList(long userID, List<long> fileIDS, int num)
        {
            bool res = false;
            DbTransaction transactionObj = null;
            DbConnection conn = null;
            try
            {
                SqlDatabase db = new SqlDatabase(AppSettingsHelper.GetWebConfigValue(Constants.MusicmanConnectionString));
                conn = db.CreateConnection();
                conn.Open();
                transactionObj = conn.BeginTransaction();

                foreach (long fileID in fileIDS)
                {
                    res = PendingDownloadsDAO.RemovePendingDownload(userID, fileID, transactionObj, db);
                    if (num != 0)
                    {
                        res = res & PendingDownloadsDAO.UpdateDownloadStats(userID, fileID, num, transactionObj, db);
                    }
                }
                transactionObj.Commit();
                transactionObj.Dispose();
                conn.Close();
                conn.Dispose();
            }
            catch (Exception ex)
            {
                res = false;
                if (transactionObj != null)
                {
                    transactionObj.Rollback();
                    transactionObj.Dispose();
                }
                if (conn != null & conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                    conn.Dispose();
                }
                LogManager.LogException("Unable to create new user", ex);
            }
            return res;
        }

        public bool UpdateDownloadStats(long personID, long searchFirleID, int num)
        {
            bool res = false;
            try
            {
                res = PendingDownloadsDAO.UpdateDownloadStats(personID, searchFirleID, num);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Error updating download stats ", ex);
            }
            return res;
        }

        #endregion

        #region userFeedback
        public List<DateTime> LoadUserFeedBackDates()
        {
            List<DateTime> res = null;
            try
            {
                res = UserfeedbackDAO.LoadFeedBackDates();
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to laod user feedback list ", ex);
            }
            return res;
        }

        public List<Userfeedback> LoadLatestFeedback(int top)
        {
            List<Userfeedback> res = null;
            try
            {
                string prefix = String.Format(" TOP {0} ", top);
                string orderBy = " ORDER BY userFeedback.DATE DESC ";
                res = UserfeedbackDAO.LoadUserfeedbacks(prefix, "", orderBy);
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to load top user feedbacks", ex);
            }
            return res;
        }

        public List<Userfeedback> LoadFeedBackPerDay(string day)
        {
            List<Userfeedback> res = null;
            try
            {
                string where = String.Format(@" where + convert(varchar, datepart(yy, userFeedback.date)) + '-' 
+ convert(varchar, datepart(mm, userFeedback.date)) + '-' 
+ convert(varchar, datepart(dd, userFeedback.date)) = '{0}' ", day);
                string orderBy = " ORDER BY userFeedback.DATE DESC ";
                res = UserfeedbackDAO.LoadUserfeedbacks("", where, orderBy);
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Unable to load top user feedbacks", ex);
            }
            return res;
        }

        public bool SaveUserFeedback(long id, long personID, string subject, string feedback)
        {
            bool res = true;
            try
            {
                Userfeedback ufb = new Userfeedback();
                ufb.Id = id;
                ufb.Personid = personID;
                ufb.Subject = subject;
                ufb.Feedback = feedback;
                ufb.Date = DateTime.Now;
                res = UserfeedbackDAO.SaveUserfeedback(ufb);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to load top user feedbacks", ex);
            }
            return res;
        }

        public bool SaveUserFeedback(Userfeedback ufb)
        {
            bool res = true;
            try
            {
                res = UserfeedbackDAO.SaveUserfeedback(ufb);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to load top user feedbacks", ex);
            }
            return res;
        }

        public bool InserUserFeedBack(Userfeedback ufb)
        {
            bool res = true;
            try
            {
                res = UserfeedbackDAO.InsertUserfeedback(ufb);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable to load top user feedbacks", ex);
            }
            return res;
        }

        public bool DeleteUserFeedback(long ID)
        {
            bool res = true;
            try
            {
                res = UserfeedbackDAO.DeleteUserfeedback(ID);
            }
            catch (Exception ex)
            {
                res = false;
                LogManager.LogException("Unable delete user feedback", ex);
            }
            return res;
        }

        #endregion

        #region UserActivity

        public UserActivity GetUserActivity(long personID)
        {
            UserActivity res = null;
            try
            {
                res = UserActivityDAO.GetUserActivity(personID);
            }
            catch (Exception ex)
            {
                res = null;
                LogManager.LogException("Error loading user activity ", ex);
            }
            return res;
        }

        public List<UserActivity> GetTopLoggers(long personid, int top)
        {
            List<UserActivity> res = new List<UserActivity>();
            if (personid != 0)
            {
                try
                {
                    string topStr = (top == 0) ? "" : String.Format(" TOP {0} ", top);
                    string orderBy = " ORDER BY (US.NUMLOGSWEB + US.NUMLOGSCLIENT) DESC";
                    res = UserActivityDAO.GetUserActivities(topStr, "", orderBy);
                }
                catch (Exception ex)
                {
                    res = null;
                    LogManager.LogException("Unable to load top 5 loggers ", ex);
                }
            }
            return res;
        }

        public List<UserActivity> GetTopDownloaders(long personid, int top)
        {
            List<UserActivity> res = new List<UserActivity>();
            if (personid != 0)
            {
                try
                {
                    string topStr = (top == 0) ? "" : String.Format(" TOP {0} ", top);
                    string orderBy = " ORDER BY US.TOTALFILES DESC";
                    res = UserActivityDAO.GetUserActivities(topStr, "", orderBy);
                }
                catch (Exception ex)
                {
                    res = null;
                    LogManager.LogException("Unable to load top 5 loggers ", ex);
                }
            }
            return res;
        }
        #endregion

        #endregion

    }

}
